﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using System.Threading;

namespace MayhemWinPhone
{
    public partial class MainPage : PhoneApplicationPage
    {
        Storyboard sbBrowserFadeOut;
        Storyboard sbBrowserFadeIn;

        DispatcherTimer timerTimeout;
        DispatcherTimer timerConnect;

        int ipAttempt = 0;

		// If this is true, say connecting,
		// otherwise, say "please verify"
		bool connectMessage;

        public MainPage()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            sbBrowserFadeOut = new Storyboard();
            sbBrowserFadeOut.Duration = new Duration(TimeSpan.FromSeconds(0.5));
            sbBrowserFadeOut.Children.Add(new DoubleAnimation() { Duration = new Duration(TimeSpan.FromSeconds(0.5)), To = 0 });
            Storyboard.SetTarget(sbBrowserFadeOut, webBrowser1);
            Storyboard.SetTargetProperty(sbBrowserFadeOut, new PropertyPath("UIElement.Opacity"));

            sbBrowserFadeIn = new Storyboard();
            sbBrowserFadeIn.Duration = new Duration(TimeSpan.FromSeconds(0.5));
            sbBrowserFadeIn.Children.Add(new DoubleAnimation() { Duration = new Duration(TimeSpan.FromSeconds(0.5)), To = 1 });
            Storyboard.SetTarget(sbBrowserFadeIn, webBrowser1);
            Storyboard.SetTargetProperty(sbBrowserFadeIn, new PropertyPath("UIElement.Opacity"));

            timerTimeout = new DispatcherTimer();
            timerTimeout.Interval = TimeSpan.FromSeconds(2);
            timerTimeout.Tick += new EventHandler(timerTimeout_Tick);

            timerConnect = new DispatcherTimer();
            timerConnect.Interval = TimeSpan.FromSeconds(0.5);
            timerConnect.Tick += new EventHandler(timerConnect_Tick);

            progressBar1.IsIndeterminate = true;

            webBrowser1.IsScriptEnabled = true;
            webBrowser1.Background = new SolidColorBrush(Colors.Black);
            webBrowser1.LoadCompleted += new LoadCompletedEventHandler(webBrowser1_LoadCompleted);
            webBrowser1.Navigating += new EventHandler<NavigatingEventArgs>(webBrowser1_Navigating);
            webBrowser1.Navigated += new EventHandler<NavigationEventArgs>(webBrowser1_Navigated);
            webBrowser1.ScriptNotify += new EventHandler<NotifyEventArgs>(webBrowser1_ScriptNotify);
            webBrowser1.Opacity = 0;

            string ip = SavedData.IP;

            if (ip == null || ip == "")
            {
				progressBar1.Visibility = Visibility.Collapsed;
				textBlockStatus.Text = "Please configure..."; 
            }
            else
            {
                Connect();
            }
        }

        void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
        {
            //Log.Write("webBrowser1_ScriptNotify");
            if (e.Value == "mayhem:error")
            {
                SetError();
            }
        }

        void Connect()
        {
            timerTimeout.Stop();
            // TODO: Handle error when this is not in view
            //Log.Write("Connect");

			if (ipAttempt == 0)
			{
				if (connectMessage)
				{
					textBlockStatus.Text = "Connecting...";
				}
				else
				{
					textBlockStatus.Text = "Unable to connect, please verify settings";
				}

				connectMessage = !connectMessage;
			}

            textBlockStatus.Opacity = 1;
            //textBlockStatus.Foreground = new SolidColorBrush(Colors.Gray);
            try
            {
                string ip = SavedData.IP;
                if (SavedData.IP.Contains(';'))
                {
                    string[] ips = SavedData.IP.Split(';');
                    if (++ipAttempt > ips.Length - 1)
					{
                        ipAttempt = 0;
					}

                    ip = ips[ipAttempt];
					if (ipAttempt != 0)
					{
						textBlockStatus.Text = string.Format("Attempting to connect, IP {0} of {1}", ipAttempt + 1, ips.Length);
					}
                }
                webBrowser1.Navigate(new Uri("http://" + ip + ":" + SavedData.Port + "/Mayhem/Html?t=" + DateTime.Now.Ticks));
            }
            catch
            {
            }
            timerTimeout.Start();
            progressBar1.Visibility = Visibility.Visible;
        }

        void SetError()
        {
            //Log.Write("SetError");
            timerTimeout.Stop();
            sbBrowserFadeOut.Begin();
            //Debug.WriteLine("Timer ticked");
            //textBlockStatus.Text = "Error connecting...";
            //textBlockStatus.Opacity = 1;
            //textBlockStatus.Foreground = new SolidColorBrush(Colors.Red);
            timerConnect.Start();
        }

        void timerTimeout_Tick(object sender, EventArgs e)
        {
            //Log.Write("timerTimeout_Tick");
            timerTimeout.Stop();
            SetError();
        }

        void timerConnect_Tick(object sender, EventArgs e)
        {
            //Log.Write("timerConnect_Tick");
            timerConnect.Stop();
            Connect();
        }

        void webBrowser1_Navigated(object sender, NavigationEventArgs e)
        {
            //Log.Write("webBrowser1_Navigated");
            timerTimeout.Stop();
            timerConnect.Stop();
            if (webBrowser1.Source.OriginalString.StartsWith("res://"))
            {
                SetError();
            }
            else
            {
                if (SavedData.IP.Contains(';'))
                {
                    string[] ips = SavedData.IP.Split(';');
                    SavedData.IP = ips[ipAttempt];
                }

                progressBar1.Visibility = Visibility.Collapsed;
                //Debug.WriteLine("Navigated to " + e.Uri + " " + e.Content + " " + webBrowser1.Source);
                textBlockStatus.Text = "";
                textBlockStatus.Opacity = 0;
                sbBrowserFadeIn.Begin();
            }
        }

        void webBrowser1_Navigating(object sender, NavigatingEventArgs e)
        {
            //Log.Write("Navigating to " + e.Uri);
            //Debug.WriteLine("Navigating to " + e.Uri);
        }

        void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
        {
            //Log.Write("Load completed " + e.Uri);
            //Debug.WriteLine("Load completed " + e.Uri);
        }

        private void Settings_Click(object sender, EventArgs e)
        {
            //Log.Write("Settings_Click");
            NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.RelativeOrAbsolute));
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            //Log.Write("OnNavigatingFrom MainPage");
            base.OnNavigatingFrom(e);
            timerConnect.Stop();
            timerTimeout.Stop();
        }

        private void rect_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {

        }
    }
}